package com.zzq.demo.excel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author : zhaoziqian
 * @description :
 * @date : 2019/7/1 10:14
 */
public class ExcelWriterFactory extends ExcelWriter {
    private OutputStream outputStream;
    private int sheetNo = 1;

    public ExcelWriterFactory(OutputStream outputStream, ExcelTypeEnum typeEnum) {
        super(outputStream, typeEnum);
        this.outputStream = outputStream;
    }

    public ExcelWriterFactory write(MultiSheetExcel multiSheetExcel) {
        return write(multiSheetExcel.getList(), multiSheetExcel.getSheetName(), multiSheetExcel.getClazz());
    }

    public ExcelWriterFactory write(List<? extends BaseRowModel> list, String sheetName, Class<? extends BaseRowModel> clazz) {
        this.sheetNo++;
        try {
            Sheet sheet = new Sheet(sheetNo, 0, clazz);
            sheet.setSheetName(sheetName);
            this.write(list, sheet);
        } catch (Exception ex) {
            try {
                outputStream.flush();
            } catch (IOException e) {
                //do something
            }
        }
        return this;
    }

    @Override
    public void finish() {
        super.finish();
        try {
            outputStream.flush();
        } catch (IOException e) {
            //do something
        }
    }

    public void close() {
        try {
            outputStream.close();
        } catch (IOException e) {
            //do something
        }
    }
}